package com.servlet;



import com.pojo.User;
import com.service.UserService;
import com.service.impl.UserServiceImpl;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zxl
 * @create :2022/9/28
 */

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.设置编码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        //2.获取请求的参数  String
       String username= request.getParameter("username");
       String password=request.getParameter("password");
        String code =request.getParameter("checkCode");

        System.out.println(username);




        //5.判断结果并执行相关操作
        if(!request.getSession().getAttribute("creatCode").equals(code)){
            request.setAttribute("rmgs","验证码错误");
            //表示验证码不通过
            request.getRequestDispatcher("register.jsp").forward(request,response);
            return;
        }
        //通过验证码
         //检查用户名
        User existsName = userService.findExistsName(username);
        if (existsName != null) {
          //用户名存在
            request.setAttribute("rumsg","用户存在");
            //表示不通过
            request.getRequestDispatcher("/register.jsp").forward(request,response);
            return;
        }
        //可用

        //注册
      User user =new User(username,password);
        boolean register =userService.register(user);
        if (register){
            //成功
            request.setAttribute("username",username);
            request.setAttribute("msg","注册成功请登录");
            request.getRequestDispatcher("/login.jsp").forward(request,response);

        }else {
            //失败
            request.setAttribute("err","注册失败");
            request.getRequestDispatcher("/register.jsp").forward(request,response);
        }
        }

}
